<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="供应商" prop="supplierName">
        <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="供应商名称" align="center" prop="supplierName">
        <template slot-scope="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.editForm.supplierName" placeholder="请输入供应商名称" />
          <span v-else>{{ scope.row.supplierName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品" align="center" prop="goodsName">
        <template slot-scope="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.editForm.goodsName" placeholder="请输入商品名称" />
          <span v-else>{{ scope.row.goodsName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="规格" align="center" prop="specification">
        <template slot-scope="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.editForm.specification" placeholder="请输入规格" />
          <span v-else>{{ scope.row.specification }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="contactInfo">
        <template slot-scope="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.editForm.contactInfo" placeholder="请输入联系方式" />
          <span v-else>{{ scope.row.contactInfo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.editForm.remark" type="textarea" placeholder="请输入备注" />
          <span v-else>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <template v-if="scope.row.editing">
            <el-button size="mini" type="text" icon="el-icon-check" @click="confirmEdit(scope.row)">保存</el-button>
            <el-button size="mini" type="text" icon="el-icon-close" @click="cancelEdit(scope.row)">取消</el-button>
          </template>
          <template v-else>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="startEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>
<script>
import { parseTime } from "@/utils/ruoyi";
import { listSupplier, getSupplier, delSupplier, addSupplier, updateSupplier } from "@/api/system/supplier";

export default {
  name: "Supplier",
  data() {
    return {
      loading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      typeList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierName: undefined,
        goodsName: undefined
      },
      rules: {
        supplierName: [{ required: true, message: "供应商名称不能为空", trigger: "blur" }],
        goodsName: [{ required: true, message: "商品不能为空", trigger: "blur" }],
        contactInfo: [{ required: true, message: "联系方式不能为空", trigger: "blur" }]
      },
      newSupplierTemplate: {
        supplierId: undefined,
        supplierName: "",
        goodsName: "",
        specification: "",
        contactInfo: "",
        remark: "",
        editing: true,
        isNew: true,
        editForm: {
          supplierName: "",
          goodsName: "",
          specification: "",
          contactInfo: "",
          remark: ""
        }
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listSupplier(this.queryParams).then(response => {
        this.typeList = response.rows.map(item => ({
          ...item,
          editing: false,
          editForm: { ...item }
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      // 添加新行到表格顶部
      this.typeList.unshift({
        ...this.newSupplierTemplate,
        editForm: { ...this.newSupplierTemplate.editForm }
      });
    },
    startEdit(row) {
      row.editing = true;
      row.editForm = { ...row };
    },
    cancelEdit(row) {
      if (row.isNew) {
        // 如果是新增行，直接移除
        this.typeList = this.typeList.filter(item => item !== row);
      } else {
        // 恢复原始数据
        row.editing = false;
      }
    },
    confirmEdit(row) {
      // 简单验证
      if (!row.editForm.supplierName || !row.editForm.goodsName || !row.editForm.contactInfo) {
        this.$message.error('请填写完整信息');
        return;
      }

      const action = row.isNew ? addSupplier : updateSupplier;
      const formData = { ...row.editForm };
      if (!row.isNew) {
        formData.supplierId = row.supplierId;
      }

      action(formData).then(() => {
        this.$modal.msgSuccess(row.isNew ? "新增成功" : "修改成功");
        // 更新行数据
        Object.assign(row, {
          ...formData,
          editing: false,
          isNew: false
        });
        // 如果是新增，重新获取列表确保数据一致
        if (row.isNew) {
          this.getList();
        }
      });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.supplierId);
      this.single = selection.length !== 1;
      this.multiple = selection.length === 0;
    },
    handleDelete(row) {
      const supplierIds = row.supplierId || this.ids;
      this.$modal.confirm("是否确认删除选中的供应商信息？").then(() => {
        return delSupplier(supplierIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/supplier/export', {
        ...this.queryParams
      }, `supplier_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>